import asyncio
import random

import pygame
from pygame import sprite

import cfg
from debug import debug
from gophers.gopher import Gopher
from gophers.hammer import Hammer
from units.uiUtil import playMyBgMusic, gameBgImg, drawText

bg = pygame.image.load('gophers/img/myGameBg.jpg')
didongImg = pygame.image.load('gophers/img/didong.png')
didongImg1 = pygame.image.load('gophers/img/didong1.png')
gopherImg = pygame.image.load('gophers/img/dishu.png')
hammerImg = pygame.image.load('gophers/img/hammer.png')

dong = pygame.mixer.Sound('gophers/music/m1.mp3')

class MainGophers:
    def __init__(self, dims, FPS = 60):
        self.dims = dims
        self.FPS = FPS
        # 记录时间
        self.start_time = pygame.time.get_ticks()
        # 游戏运行控制变量（gamen_running）
        self.game_running = True
        # 得分
        self.source = 0
        # 地鼠精灵组
        self.gophersGroup = pygame.sprite.Group()
        # 锤子
        self.hammer = Hammer(self.dims, (200,200), hammerImg, 0,(self.dims[0]/2, self.dims[1]/2))

    def drewImg(self, screen, img, size, position):
        _gopherImg = pygame.transform.scale(img, size)
        screen.blit(_gopherImg, position)

    # 游戏主循环所在函数需要由 async 定义
    async def start(self):
        # 初始化游戏界面（screen）：尺寸、背景色等
        screen = pygame.display.set_mode(self.dims)
        # 显示游戏名称
        pygame.display.set_caption("打地鼠")
        # 初始化游戏时钟（clock），由于控制游戏帧率
        clock = pygame.time.Clock()
        # 播放背景音乐
        playMyBgMusic('assets/music/bg3.mp3')

        tempx = random.randint(0,2)
        tempy = random.randint(0, 2)
        gopherSprite = Gopher(gopherImg, self.dims, (200,200), (30 + 30*tempx+ tempx*200, 300 + tempy*300))
        self.gophersGroup.add(gopherSprite)

        # 游戏主循环
        while cfg.inGame:
            # 按照给定的 FPS 刷新游戏
            # clock.tick() 函数返回上一次调用该函数后经历的时间，单位为毫秒 ms
            # dt 记录上一帧接受之后经历的时间，单位为秒 m
            # 使用 dt 控制物体运动可以使游戏物理过程与帧率无关
            dt = clock.tick(self.FPS) / 1000.0
            # 使用 asyncio 同步
            # 此外游戏主体代码中不需要再考虑 asyncio
            await asyncio.sleep(0)

            # 游戏事件处理
            # 包括键盘、鼠标输入等
            for event in pygame.event.get():
                # 点击关闭窗口按钮或关闭网页
                if event.type == pygame.QUIT:
                    pygame.quit()
                # 当 game_running 为 False 时，

            # 调用 debug 函数在游戏界面左上角显示游戏帧率
            debug(f"{clock.get_fps():.1f}", color='green')
            # 更新背景
            gameBgImg(screen, bg, 0, self.dims)
            # 显示得分
            drawText(f"得分：{self.source}", "black", (100, 100), screen)
            #画地鼠的洞洞
            for i in range(0,3):
                for j in range(0,3):
                    self.drewImg(screen, didongImg, (200, 200), (30 + 30*i + i*200, 300 + j*300))

            # 随机出来一只地鼠
            for gopherSprite in self.gophersGroup:
                if not gopherSprite.update():
                    self.gophersGroup.remove(gopherSprite)
            if self.gophersGroup.__len__() == 0:
                tempx = random.randint(0, 2)
                tempy = random.randint(0, 2)
                gopherSprite = Gopher(gopherImg, self.dims, (200, 200),
                                      (30 + 30 * tempx + tempx * 200, 300 + tempy * 300))
                self.gophersGroup.add(gopherSprite)

            self.gophersGroup.draw(screen)

            # 画地鼠的洞洞
            for i in range(0, 3):
                for j in range(0, 3):
                    self.drewImg(screen, didongImg1, (200, 200), (30 + 30 * i + i * 200, 300 + j * 300))
            # 让锤子跟随鼠标移动
            for event in pygame.event.get():
                # 点击关闭窗口按钮或关闭网页
                if event.type == pygame.QUIT:
                    pygame.quit()
                if event.type == pygame.MOUSEMOTION:
                    # 获取鼠标位置
                    x, y = pygame.mouse.get_pos()
                    self.hammer.rect.x = x
                    self.hammer.rect.y = y-100
                if event.type == pygame.MOUSEBUTTONDOWN:
                    dong.play()
                    mouse_pos = pygame.mouse.get_pos()
                    # 检测精灵是否被点击
                    for gopherSprite in self.gophersGroup:
                        if mouse_pos[0]>gopherSprite.rect[0] and mouse_pos[0]<gopherSprite.rect[0]+200 and mouse_pos[1]>gopherSprite.rect[1] and mouse_pos[1]<gopherSprite.rect[1]+200:
                            self.gophersGroup.remove(gopherSprite)
                            self.source += 1

            # 画个锤子
            self.hammer.draw(screen)

            # 将游戏界面内容输出至屏幕
            pygame.display.update()

            # 跳出游戏主循环，退出游戏
        cfg.inGame = False